﻿using AdminSystem.Domain;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdminSystem.EntityFrameworkCore
{
    public class AdminSystemDbContext : DbContext
    {
        public AdminSystemDbContext(DbContextOptions options) : base(options)
        {

        }

        public DbSet<Admin> Admins { get; set; }

        public DbSet<Address> Addresses { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //配置数据库字段
            modelBuilder.Entity<Admin>(build => {
                build.Property(x => x.UserName).HasMaxLength(50).IsRequired().IsFixedLength().IsUnicode();
                build.Property(x => x.Password).HasMaxLength(50).IsRequired();
            });


            //数据播种,配置逻辑删除过滤
            modelBuilder.Entity<Admin>()
                .HasQueryFilter(x=>x.IsDeleted == false)
                .HasData(
                new Admin 
                {
                    AdminId = 1,
                    CreateName = "张三",
                    CreateTime = DateTime.Now.AddDays(-10),
                    Gender = Gender.Girl,
                    IsDeleted = false,
                    Password = Guid.NewGuid().ToString("n"),
                    UserName = "Admin"
                },
                new Admin
                {
                    AdminId = 2,
                    CreateName = "李四",
                    CreateTime = DateTime.Now.AddDays(-5),
                    Gender = Gender.Boy,
                    IsDeleted = false,
                    Password = Guid.NewGuid().ToString("n"),
                    UserName = "lisi"
                }
                );


            //配置数据库字段
            modelBuilder.Entity<Address>(build =>
            {
                build.Property(x => x.Mobile).HasMaxLength(50).IsRequired();
                build.Property(x => x.Province).IsRequired();
                build.Property(x => x.Area).HasMaxLength(50).IsRequired();
                build.Property(x => x.Email).HasMaxLength(50).IsRequired();
                build.Property(x => x.City).HasMaxLength(50).IsRequired();
                build.Property(x => x.Detail).HasMaxLength(50).IsRequired();

                // 配置外键
                build.HasOne(x => x.Admin).WithMany().HasForeignKey(x => x.AdminId);
            });


            base.OnModelCreating(modelBuilder);
        }
    }
}
